# -*- coding: utf-8 -*-
"""Misc utilities"""

import datetime

class Wrapper(object):
    """
    Wraps up dictionaries, internal class. Lets you use getattr
    just like getitem.
    """
    def __init__(self, _wrapped=None, **kw):
        if _wrapped:
            self._d = _wrapped
        else:
            self._d = {}
        self._d.update(kw)
    def __delitem__(self, key):
        del self._d[key]
    def __getattribute__(self, key):
        try:
            return object.__getattribute__(self, key)
        except AttributeError:
            try:
                return self[key]
            except KeyError, exc:
                raise AttributeError, exc

    def __getitem__(self, key):
        return self._d[key]
    def __setitem__(self, key, value):
        self._d[key] = value
    def __contains__(self, key):
        return self._d.__contains__(key)
    def __setattr__(self, key, value):
        if key[0] == "_":
            object.__setattr__(self, key, value)
        else:
            self._d[key] = value
    def pop(self, key):
        return self._d.pop(key)
    def get(self, *args, **kwargs):
        return self._d.get(*args, **kwargs)
    def clear(self):
        self._d.clear()
    def keys(self):
        return self._d.keys()
    def items(self):
        return self._d.items()
    def values(self):
        return self._d.values()
    def has_key(self, k):
        return self._d.has_key(k)
    def __repr__(self):
        return self._d.__repr__()
    def __str__(self):
        return self._d.__str__()
    def get_dict(self):
        return self._d


class MonthYear:
    def __init__(self, month=datetime.date.today().month, year=datetime.date.today().year):
        self.month = month
        self.year = year

    def __str__(self):
        return "%02d.%04d" % (self.month, self.year)

    def to_int(self):
        return self.month - 1 + (self.year * 12)

    @classmethod
    def from_int(cls, i):
        i = int(i)
        return cls(month=(i % 12) + 1, year=i / 12)

    @classmethod
    def iterate(cls, from_my, to_my):
        for i in range(from_my.to_int(), to_my.to_int() + 1):
            yield cls.from_int(i)

    @classmethod
    def get_academic_year_begin(cls):
        now = datetime.date.today()
        if now.month <= 8:
            return MonthYear(month=9, year=now.year - 1)
        else:
            return MonthYear(month=9, year=now.year)

    @classmethod
    def get_academic_year_end(cls):
        now = datetime.date.today()
        if now.month <= 8:
            return MonthYear(month=5, year=now.year)
        else:
            return MonthYear(month=5, year=now.year + 1)

    def get_begin_month(self):
        return datetime.date(self.year, self.month, 1)

    def get_end_month(self):
        next = MonthYear.from_int(self.to_int() + 1)
        return next.get_begin_month() - datetime.timedelta(days=1)

    def get_next_month_year(self):
        if self.month <= 11:
            return dict(year=self.year, month=self.month+1)
        if self.month == 12:
            return dict(year=self.year+1, month=1)

    def next_month(self):
        if self.month <= 11:
            return MonthYear(year=self.year, month=self.month+1)
        if self.month == 12:
            return MonthYear(year=self.year+1, month=1)

    def get_last_day(self):
        return last_month_day(self.month, self.year)

    def __eq__(self, another_month_year):
        y = (self.year == another_month_year.year)
        m = (self.month == another_month_year.month)
        if y and m:
            return True
        return False

    def __ne__(self, another_month_year):
        return not(self == another_month_year)



class ExceptionsBunch(Exception):
    def __init__(self, pairs):
        Exception.__init__(self)

        self.pairs = pairs
        self.title = ""


class PhoneFormat(object):
    @staticmethod
    def bad_str(rus=False):
        if (rus):
            return _('Incorrectly dialed')
        return 'Incorrectly dialed'

    @staticmethod
    def to_python(value):
    
        def is_phone_from_dict(value):
            if not isinstance(value, dict):
                return False
            if not (value.has_key('code') and value.has_key('num')):
                return False
            new_value = check_empty(value)
            if len(new_value['code']) + len(new_value['num'])!=10:
                return False
            return True
                
        def check_empty(dict_value):
            num = str(dict_value['num']).strip()
            code = str(dict_value['code']).strip()
            if not (len(code) + len(num)):
                code = '000'
                num = '0000000'
            if not len(code):
                code = '0'*(10-len(num))
            if not len(num):
                num = '0'*(10-len(code))
            return dict(code=code,num=num)

        if value is None:
            return None
        if not (is_phone_from_dict(value)):
            return PhoneFormat.bad_str()
        new_value = check_empty(value)
        num = new_value['num']
        code = new_value['code']
        num_full = "%s-%s-%s"%(num[:-4],num[-4:-2],num[-2:])
        return "+7-(%s)-%s"%(code,num_full) 
    
    @staticmethod
    def from_python(value):
        if value is None:
            return None
        beg_num = value.find(')')
        return dict (code=value[4:beg_num],num=value[beg_num+2:].replace('-',''))
